package com.iotp.service.user;

import com.alibaba.fastjson.JSONObject;
import com.iotp.dao.user.CommUserMapper;
import com.iotp.dao.userOrgRef.UserOrgRefDAO;
import com.iotp.dao.userRoleRef.UserRoleRefDAO;
import com.iotp.dao.userUserRef.UserUserRefDAO;
import com.iotp.entity.user.CommUser;
import com.iotp.entity.userOrgRef.UserOrgRef;
import com.iotp.entity.userRoleRef.UserRoleRef;
import com.iotp.entity.userUserRef.UserUserRef;
import com.iotp.service.userUserRef.UserUserRefService;
import com.iotp.utils.common.DataUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

@Service("userService")
public class UserServiceImpl implements UserService {
    private static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private CommUserMapper commUserMapper;
    @Autowired
    private UserUserRefDAO userUserRefDAO;
    @Autowired
    private UserOrgRefDAO userOrgRefDAO;
    @Autowired
    private UserRoleRefDAO userRoleRefDAO;
    @Autowired
    private UserUserRefService userUserRefService;

    @Override
    public CommUser queryUserById(String userId) {
        CommUser user = this.commUserMapper.selectByPrimaryKey(userId);
        UserUserRef ur = this.userUserRefDAO.selectByOldId(user.getUserId());
        if(ur == null){
            logger.info("系统用户未关联到userUserRef表，系统用户信息,{}", JSONObject.toJSONString(user));
        }
        user.setNewuserId(ur.getId());
        return user;
    }

    @Override
    public List<CommUser> queryByConditiono(CommUser commUser) {
        return this.commUserMapper.selectByCondition(commUser);
    }

    @Override
    public CommUser queryByUserIdAndPswd(String userId, String password) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        params.put("userPassword", DataUtil.generateMD5(password.getBytes()));
        return this.commUserMapper.selectByIdAndPwd(params);
    }

    @Override
    public List<CommUser> queryIsUserExist(String userId, String account, String email) {
        CommUser query = new CommUser();
        query.setUserId(userId);
        query.setItCode(account);
        query.setEmail(email);
        return this.commUserMapper.selectByCondition(query);
    }

    @Override
    public void add(CommUser commUser) {
        UserUserRef add = new UserUserRef();
        add.setOldUserId(commUser.getUserId());
        Long newUserId = this.userUserRefService.add(add);
        commUser.setAvailable(1);
        this.commUserMapper.insert(commUser);

        // 用户添加成功，添加用户、机构关联关系
        this.userOrgRefDAO.insert(new UserOrgRef(null, newUserId, commUser.getOrgId()));

        // 用户添加成功、添加用户、角色关联关系
        String[] roleIdArr = commUser.getRoleIds().split(",");
        for(String roleId : roleIdArr) {
            if(!roleId.equals("0")) {
                this.userRoleRefDAO.insert(new UserRoleRef(null, commUser.getOrgId(), newUserId, Long.parseLong(roleId)));
            }
        }


    }

    @Override
    public void edit(CommUser commUser) {
        this.commUserMapper.updateByPrimaryKeySelective(commUser);
        UserUserRef ur = this.userUserRefDAO.selectByOldId(commUser.getUserId());
        // 检查角色信息是否更新
        List<UserRoleRef> refList = this.userRoleRefDAO.selectList(ur.getId());
        if(refList == null || refList.size() == 0) {
            String[] roleIdArr = commUser.getRoleIds().split(",");
            for(String roleId : roleIdArr) {
                if(!roleId.equals("0")) {
                    this.userRoleRefDAO.insert(new UserRoleRef(null, commUser.getOrgId(), ur.getId(), Long.parseLong(roleId)));
                }
            }
        } else {
            String currRoleIds = "";
            for(UserRoleRef ref : refList) {
                currRoleIds += ref.getRoleId().longValue() + ",";
            }
            String[] currRoleArr = currRoleIds.split(",");
            String[] roleIdArr = commUser.getRoleIds().split(",");
            if(!Arrays.equals(currRoleArr, roleIdArr)) {
                this.userRoleRefDAO.delete(ur.getId());
                for(String roleId : roleIdArr) {
                    if(!roleId.equals("0")) {
                        this.userRoleRefDAO.insert(new UserRoleRef(null, commUser.getOrgId(), ur.getId(), Long.parseLong(roleId)));
                    }
                }
            }
        }
    }

    @Override
    public void editMySelf(CommUser commUser) {
        this.commUserMapper.updateByPrimaryKeySelective(commUser);
    }

    @Override
    public void editPswd(String userId, String password) {
        CommUser edit = new CommUser();
        edit.setUserId(userId);
        edit.setUserPassword(DataUtil.generateMD5(password.getBytes()));
        this.commUserMapper.updateByPrimaryKeySelective(edit);
    }

    @Override
    public void editUserStatus(String userId, int state) {
        CommUser edit = new CommUser();
        edit.setUserId(userId);
        edit.setAvailable(state);
        this.commUserMapper.updateByPrimaryKeySelective(edit);
    }

    @Override
    public void editIsDel(String userId, int state) {
        this.commUserMapper.deleteByPrimaryKey(userId);
    }
}
